package cn.imvc.app.models;

import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import cn.imvc.app.entities.AttrClass;
import cn.imvc.app.entities.AttrValue;
import cn.imvc.app.repositories.AttrValueRepository;
import cn.imvc.data.domain.ViewRequest;
@Service
public class AttrValueModelImpl implements AttrValueModel{

	@Autowired
	AttrValueRepository attrValueRepository;
	@Autowired
	RefRelationModel refRelationModel;
	
	public Page<AttrValue> find(ViewRequest viewRequest) {
		
		return attrValueRepository.findAll(viewRequest);
	}

	public AttrValue get(int id) {
		
		return attrValueRepository.getOne(id);
	}

	public int save(int attrClassId,AttrValue attrValue) {
		String name = attrValue.getName();
		List<AttrValue> pn= attrValueRepository.findByName(name);
		if(pn.size()>0){
			return -1;
		}
		attrValueRepository.saveAndFlush(attrValue);
		return 1;
	}

	public int update(int id,AttrClass attrclass, AttrValue attrValue) {
		
		attrValue.setAttrClass(attrclass);		
		AttrValue loadAttrValue = attrValueRepository.getOne(id);
		String name = attrValue.getName();
		List<AttrValue> pn= attrValueRepository.findByName(name);
		if(pn.size()>0&&!name.equals(loadAttrValue.getName())){
			return -1;
		}
		BeanUtils.copyProperties(attrValue, loadAttrValue, new String[]{"id"});
		attrValueRepository.saveAndFlush(loadAttrValue);
		return 1;
	}

	public String delete(int id) {
		String result = refRelationModel.deleteDateCheck("Attr_Value", "id", id);
	    if(result.equals("")){
	    	attrValueRepository.delete(id);
	    	return "";
	    }else{
	    	return result;
	    }
	}

	public void delete(int[] ids) {
		for(int id:ids){
			attrValueRepository.delete(id);
		}
		
	}

	public List<AttrValue> getByAttrClassId(int attrClassId) {
		return attrValueRepository.findByAttrClassId(attrClassId);
	}





}
